import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon, AtModal, AtModalAction, AtModalContent, AtTextarea, AtModalHeader} from 'taro-ui'
import {Block, Button, Image, Text, View} from '@tarojs/components'
import {newHttp} from "../../../../utils/request";
import {http} from '../../../../utils/http'
import {
  TEAM_APPOINT_ORDER_DETAIL,
  GET_IMG,
  BASE_URL,
  TARO_ENV,
  GET_PCODE,
  TEAM_APPOINT_RECEIVE,
  TEAM_APPOINT_REJECT
} from '../../../../constants/api'
import GzhAuth from "../../../../components/gzh-auth/gzh-auth"
import {platform} from "../../../../utils/platform-settting.service";
import {h5Wx} from "../../../../utils/h5.service";
import './detail.scss'

export default class List extends Component {
  state: {
    detail: any
    tipsNum: number
    showNum: number
    customize: any
    files: any
    isRefuseOpen: boolean
    refuseData: any
    hiddenBtn: boolean
  } = {
    detail: {},
    customize: [],
    showNum: 1,
    files: [],
    isRefuseOpen: false,
    refuseData: {},
    hiddenBtn: false
  }
  orderNum
  page
  orderId
  extendPage
  supplierId
  params = Taro.getCurrentInstance().router.params

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const hiddenBtn = this.params.hiddenBtn;
    this.setState({
      hiddenBtn
    });
    await this.getDetault()
  }

  async getDetault() {
    this.orderNum = this.params.orderNum
    this.orderId = this.params.orderId
    this.page = this.params.page
    this.supplierId = this.params.supplierId
    this.extendPage = this.params.extendPage
    const detail = await http.carGet(TEAM_APPOINT_ORDER_DETAIL, {
      type: this.page,
      orderNum: this.orderNum,
      supplier_id: this.supplierId,
      orderId: this.orderId
    })
    if (platform.info.checkStyleMini && platform.info.checkStyleMini > 0 && this.page === 'seller' && this.extendPage !== 'site') {
      if (platform.info.checkStyleMini >= 1 && platform.info.checkStyleMini != 2 && TARO_ENV !== 'h5') {
        const data = await Taro.request({
          url: http.url(GET_PCODE),
          data: {orderId: detail.id, orderType: 1},
          method: 'POST',
          header: await http.getHeader({'Content-Type': 'application/x-www-form-urlencoded'})
        })
        if (data.data.orderWxPcode) {
          detail.pcodeimg = data.data.orderWxPcode
        }
      }
      if (platform.info.checkStyleMini >= 2) {
        if (detail.qrCode) {
          detail.qrcodeimg = detail.qrCode
        }
      }
    }
    if(detail.custom_item_pic){
      const files = []
      detail.custom_item_pic.split(',').forEach(item => {
        if (this.makeMap(item)) {
          files.push({ url: item })
        }
      })
      this.setState({ files })
    }
    if (detail.info_item_detail_config) {
      detail.info_item_detail_config = JSON.parse(detail.info_item_detail_config)
    }
    if(detail.info_item_detail){
      this.setState({ customize: JSON.parse(detail.info_item_detail) })
    }
    let showNum = 0
    if(detail.detail){
      showNum = detail.detail.length
    }
    this.setState({
      detail,
      showNum
    });
  }

  makeMap(item) {
    return item.includes('.png') || item.includes('.jpg') || item.includes('.gif') || item.includes('.jpeg') || item.includes('.tiff')
  }

  toggleMeals(showNum){
    const { detail } = this.state
    if(showNum==1){
      this.setState({showNum:detail.detail.length})
    }else{
      this.setState({showNum:1})
    }
  }

  // 大图预览
  maxImage(image) {
    Taro.previewImage({
      urls: [image]
    });
  }

  async doDeal(goodsId, orderNum){
    await newHttp.post(TEAM_APPOINT_RECEIVE, {goodsId, orderNum, type: 0})
    Taro.showToast({title: '接收成功', icon: 'none'});
    this.getDetault();
  }
  async confirmRefuse(){
    const {refuseData} = this.state
    await http.post(TEAM_APPOINT_REJECT, refuseData)
    Taro.showToast({title: '拒绝成功', icon: 'none'})
    this.setState({isRefuseOpen: false})
    this.getDetault();
  }
  doRefuse(goodsId, orderNum){
    const refuseData = { goodsId, orderNum, cause: '', supplier_id: this.supplierId, type: 0 }
    this.setState({isRefuseOpen:true, refuseData})
  }
  onCopy(str, e) {
    e.stopPropagation()
    try {
      Taro.setClipboardData({
        data: str
      })
      if (TARO_ENV === 'h5') {
        Taro.showToast({title: '复制成功'})
      }
    } catch (e) {
      Taro.showToast({title: '复制失败'})
    }
  }

  render() {
    const {files, detail, customize, showNum, isRefuseOpen, refuseData, hiddenBtn} = this.state
    return (
      <View className='my-reverse appoint-list-root'>
        <GzhAuth />
        <View className='content'>
          <View className='item'>
            <View className='title-box'>
              <View className='title-box-status'>
                {detail.status === 0 && <Text>待接收</Text>}
                {detail.status === 1 && <Text>已接收</Text>}
                {detail.status === 2 && <Text>已拒绝</Text>}
                {detail.status === 3 && <Text>已完成</Text>}
              </View>
              <View className='title'>
                <View className={`${TARO_ENV}`}>{detail.goods_name}</View>
              </View>
              <View className='line' />
              {(detail.status === 3 || detail.status === 1) && this.page === 'seller' && this.extendPage !== 'site' &&
              <View className={detail.status === 3 ? 'onle-ticket filter' : 'onle-ticket'}>
                <View className={`ticket-top-order ${TARO_ENV}`}
                  onClick={this.onCopy.bind(this, detail.order_num)}
                >订单号 {detail.order_num}<Image className='img' src='https://resource.ivcheng.com/resources/images/order_copy.png' /></View>
                <View className='code-box'>{detail.pcodeimg &&
                <Image className='qrimg' src={detail.pcodeimg} />}{detail.qrcodeimg &&
                <Image className='qrimg' src={BASE_URL + GET_IMG + detail.qrcodeimg + '&orderType=1'} />}</View>
                <View className='code-shuoming'>
                  {detail.pcodeimg && <Text>支持微信核验</Text>}
                  {detail.qrcodeimg && <Text>支持设备核验</Text>}
                </View>
              </View>
              }
              {detail.supplierName && this.page === 'seller' &&
              <View className='time'>{process.env.fxName}姓名：{detail.supplierName}</View>}
              <View className='time'>订单号：{detail.order_num}</View>
              { detail.info_item_detail_config && detail.info_item_detail_config.reserve_date && <View className='time'>预约时间：{detail.reserve_date}</View>}
              { detail.info_item_detail_config && detail.info_item_detail_config.in_date && <View className='time'>入场时间：{detail.inDate}</View>}
              { detail.info_item_detail_config && detail.info_item_detail_config.team_org && <View className='time'>组团单位：{detail.team_org}</View>}
              { detail.info_item_detail_config && detail.info_item_detail_config.linkman && <View className='time'>领队姓名：{detail.linkman}</View>}
              { detail.info_item_detail_config && detail.info_item_detail_config.link_phone && <View className='time'>领队电话：{detail.link_phone}</View>}
              { detail.info_item_detail_config && detail.info_item_detail_config.team_address && <View className='time'>客源地：{detail.team_address}</View>}
              { detail.info_item_detail_config && detail.info_item_detail_config.guide_num && <View className='time'>讲解员人数：{detail.guide_num}</View>}
              { detail.info_item_detail_config && detail.info_item_detail_config.is_reserve_meal && <View className='time'>是否订餐：{!!detail.is_reserve_meal ? '是' : '否'}</View>}
              { detail.info_item_detail_config && detail.info_item_detail_config.custom_num && <View className='time'>预约人数：{detail.custom_num}</View>}
              { detail.cause && <View className='time'>拒绝原因：{detail.cause}</View>}
              {detail.status === 3 && <View className='time'>实际人数：{detail.real_custom_num}</View>}
              { customize && customize.length > 0 && customize.map(item=> <View className='time'>{ item.title }：{item.value}</View>) }
              {
                files && files.length >0 &&
                <View className='time files'>
                  用户上传图片：
                  <View className='image_wrap' onClick={() => {this.maxImage(files[0].url)}}>
                    <Image className='img' src={files[0].url} mode='widthFix' lazyLoad />
                    <AtIcon value='search' size='30' color='#fff' className='icon_circle' />
                  </View>
                </View> }
              {detail.detail && detail.detail.length > 0 && <View className='line' />}
              {detail.detail && detail.detail.length > 0 &&
              <View className='tourist-information'>
                <View className='title'>游客信息</View>
                {detail.detail.map((item, i) =>
                  <Block>
                    {i < showNum && <View className='items'>
                      <View className='time'>姓名：{item.name}</View>
                      <View className='time'>手机号：{item.phone}</View>
                      {item.idcard && <View className='time'>证件号：{item.idcard}</View>}
                      </View>}
                  </Block>)}
                {detail.detail.length>1 && <View className='good_meals_more' onClick={this.toggleMeals.bind(this,showNum)}>{showNum>1?<Block>收起<AtIcon value='chevron-up' size='15' color='#999' /></Block>:<Block>查看更多<AtIcon value='chevron-down' size='15' color='#999' /></Block>}</View>}
              </View>}
            </View>
          </View>
        </View>
        {!hiddenBtn && <View className='bottom'>
          {detail.status === 0 && !detail.third_supplier_order_num &&
          <View className='arrangement' onClick={this.doDeal.bind(this, detail.goods_id, detail.order_num)}>
            <View className='arrangement-btn'>接收</View>
          </View>}
          {detail.status === 0 && !detail.third_supplier_order_num &&
          <View className='arrangement' onClick={this.doRefuse.bind(this, detail.goods_id, detail.order_num)}>
            <View className='arrangement-btn'>拒绝</View>
          </View>}
        </View>}
        {isRefuseOpen && <AtModal className='model' isOpened={isRefuseOpen}>
          <AtModalHeader>拒绝原因<AtIcon onClick={() => {
            this.setState({isRefuseOpen: false})
          }} className='close-cla' value='close' size='20' color='#888888'
          /></AtModalHeader>
          <AtModalContent>
            <AtTextarea
              onChange={value => {
                refuseData['cause'] = value
                this.setState({ refuseData });
              }}
              count={false}
              value={refuseData.cause}
              maxLength={200}
              placeholder='请输入拒绝原因'
            />
          </AtModalContent>
          <AtModalAction><Button className='readed' onClick={this.confirmRefuse.bind(this)}>确定</Button> </AtModalAction>
        </AtModal>}
      </View>
    )
  }
}
